package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.BaseDTO;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.entity.MyPage;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    CategoryBrandService categoryBrandService;

    @Override
    public PageDTO findPyPage(MyPage myPage) {
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Brand> brandPage;
        if(myPage.getKey()!=null){
            queryWrapper.like("name", myPage.getKey());
            brandPage = this.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<Brand>(Integer.parseInt(myPage.getPage()), Integer.parseInt(myPage.getRows())), queryWrapper);

        }else {
            brandPage = this.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<Brand>(Integer.parseInt(myPage.getPage()), Integer.parseInt(myPage.getRows())));

        }

        return new PageDTO(brandPage.getTotal(),brandPage.getTotal()/brandPage.getSize()+1,brandPage.getRecords());
    }

    @Override
    public List<BrandDTO> getBrandByIds(List<Long> ids) {
        List<Brand> brands = this.listByIds(ids);
        return  BrandDTO.convertEntityList(brands);
    }

    @Override
    public List<BrandDTO> getBrandByCategoryId(Long id) {
        List<CategoryBrand> categorys = categoryBrandService.query().eq("category_id", id).list();
        List<Long> brandIds = categorys.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());
        return  BrandDTO.convertEntityList(this.listByIds(brandIds));
    }

    @Override
    public BrandDTO getBrandById(Long id) {
        Brand brand = this.getById(id);
        return  new BrandDTO(brand);
    }

    @Override
    @Transactional
    public void createBrand(Brand brand, List<Long> categoryIds) {
        this.saveOrUpdate(brand);
        List<CategoryBrand> categoryBrands = categoryIds.stream().map(category -> CategoryBrand.of(category, brand.getId())).collect(Collectors.toList());
        categoryBrandService.saveOrUpdateBatch(categoryBrands);
    }

    @Override
    public void updateBrand(Brand brand, List<Long> categoryIds) {
        // 1.更新品牌
        boolean success = updateById(brand);
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500, "更新品牌失败！");
        }
        // 2.根据品牌id删除中间表数据
        success = categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500,"更新品牌失败，删除中间表数据出错");
        }
        // 3.重新插入中间表数据
        List<CategoryBrand> list = categoryIds.stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(list);

    }
}